package com.qu.tabhost.base;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import com.qu.tabhost.OnReselectListener;
import com.qu.tabhost.R;

import java.security.PublicKey;

import butterknife.BindView;

/**
 * Created by quguangle on 2017/5/17.
 * ViewPagerFragment的基类
 */

public abstract class BaseViewPagerFragment extends BaseFragment{
    public static final String BASEVIEWPAGERBUNDLE = "BUNDLE";
    @BindView(R.id.tab_nav)
    TabLayout tabLayout;
    @BindView(R.id.base_viewPager)
    ViewPager viewPager;
    @Override
    protected int getLayout() {
        return R.layout.base_viewpager_layout;
    }
    @Override
    protected void initWidget(View mRoot) {
        super.initWidget(mRoot);
        BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(getChildFragmentManager(),getPages());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(0,true);
    }
    public static class PageInfo{
        private String title;
        private Class<?> clx;
        private Bundle args;
        public PageInfo(String title,Class<?> clx,Bundle args){
            this.title = title;
            this.clx = clx;
            this.args = args;
        }
    }
    public abstract PageInfo[] getPages();

   private class BaseViewPagerAdapter extends FragmentPagerAdapter{
       private Fragment mCurrentFragment;
       private PageInfo[] mPageInfos;
       public BaseViewPagerAdapter(FragmentManager fm,PageInfo[] mPageInfos) {
           super(fm);
           this.mPageInfos = mPageInfos;
       }
       //得到当前显示的Fragment
       @Override
       public void setPrimaryItem(ViewGroup container, int position, Object object) {
           super.setPrimaryItem(container, position, object);
           if(object instanceof Fragment){
               mCurrentFragment = (Fragment) object;
           }
       }

       @Override
       public Fragment getItem(int position) {
              PageInfo mCurrentPage = mPageInfos[position];
              Fragment fragment = Fragment.instantiate(getContext(),
                      mCurrentPage.clx.getName(),mCurrentPage.args);
           return fragment;
       }

       @Override
       public int getCount() {
           return mPageInfos.length;
       }

       @Override
       public CharSequence getPageTitle(int position) {
           return mPageInfos[position].title;
       }

       @Override
       public int getItemPosition(Object object) {
           return PagerAdapter.POSITION_NONE;
       }

       public Fragment getmCurrentFragment(){
           return mCurrentFragment;
       }
   }
}
